<!--
author: 何其沆(pooky)
desc: Pool - Account Pool
date: 2021-11-12
-->
<template>
  <div class="account-pool">
    <search @search="handleSearch" @reset="handleReset">
      <div style="display: flex">
        <SearchInput searchText="Client Name">
          <a-input v-model:value="clientName" placeholder="Client Name / Abbreviation / Organization" />
        </SearchInput>
        <SearchInput searchText="URL">
          <a-input v-model:value="url" />
        </SearchInput>
        <SearchInput searchText="Mailbox">
          <a-input v-model:value="mailbox" />
        </SearchInput>
        <SearchInput searchText="Status">
          <a-select
            v-model:value="status"
            show-search
            option-filter-prop="label"
            option-label-prop="label"
            :get-popup-container="triggerNode => triggerNode.parentNode"
          >
            <a-select-option value="-1" label="All Client">All Client</a-select-option>
            <a-select-option value="3" label="Assigned">Assigned</a-select-option>
            <a-select-option value="2" label="Unassigned">Unassigned</a-select-option>
          </a-select>
        </SearchInput>
      </div>
    </search>
    <e-container style="margin-top: 24px">
      <div v-if="hasEditPermission" class="du-area">
        <a-button type="default" class="button" @click="handleDownload">
          <e-icon type="excel" color="green" font-size="16px" style="cursor: pointer" />
          <span style="margin-left: 8px; padding-top: 4px; color: #252526">Download Template</span>
        </a-button>
        <a-button
          primary
          class="button"
          style="background-color: #f0f2f7; border: none; margin-left: 24px"
          @click="handleImport"
        >
          <e-icon type="upload" color="#3c6cfe" font-size="16px" style="cursor: pointer" />
          <span style="margin-left: 8px; color: #3c6cfe">Import</span>
        </a-button>
        <input
          ref="uploadInput"
          type="file"
          style="display: none"
          accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
          @change="uploadFileChange"
        />
      </div>
      <a-spin :spinning="loading" tip="Loading...">
        <a-table
          :columns="columns"
          :data-source="data"
          class="ant-table-striped"
          :expandIconColumnIndex="9"
          :expanded-row-keys="expandedRowKeys"
          :pagination="false"
          :row-class-name="(_record, index) => (index % 2 === 0 ? 'table-striped' : null)"
        >
          <template #bodyCell="{ column, record }">
            <template v-if="column.key === 'tags'">
              <span v-for="(item, index) in record.tags" :key="index">
                <e-tag :item="item" />
              </span>
            </template>
            <template v-if="column.key === 'fullName'">
              <span>
                <a-tooltip>
                  <template #title> Do not contact this client </template>
                  <e-icon v-if="record.fromMLV" type="tips1" fontSize="14px" style="color: #ffaf17; cursor: help" />
                </a-tooltip>
                {{ record.fullName }}
              </span>
            </template>
          </template>
          <template #expandedRowRender="{ record }">
            <active-expend v-if="record.status === 11 && record.list" :record="record" />
            <expend v-if="record.status !== 11 && record.clientPhaseInfo" :record="record" />
          </template>
          <template #expandIcon="{ expanded, record }">
            <e-icon
              :type="expanded ? 'Hidden' : 'DropDown'"
              color="#a9b5c9"
              font-size="20px"
              style="cursor: pointer"
              @click="handleRowExpand(expanded, record)"
            />
          </template>
          <template #emptyText>
            <e-empty>
              <template #description>
                <div>Please specify at least one search filter</div>
              </template>
            </e-empty>
          </template>
        </a-table>
      </a-spin>
      <div v-if="total > 0" class="pagination">
        <a-pagination
          v-model:current="current"
          v-model:pageSize="pageSize"
          :total="total"
          show-less-items
          :show-size-changer="false"
          @change="changeSize"
        />
      </div>
    </e-container>
  </div>
</template>
<script setup>
// 引入方法
import { ref, reactive, computed, onBeforeUnmount, inject } from 'vue'
import { useStore } from 'vuex'
import { IMPORT_SUCCEEDED } from '@/constants/message.js'
import pageColumns from '@/assets/script/page_columns.js'
import Pool from '@/api/pool.js'
import Util from '@/utils'
// 引入组件
import EContainer from '@/components/EContainer.vue'
import EIcon from '@/components/EIcon.vue'
import ETag from '@/components/ETag.vue'
import EEmpty from '@/components/EEmpty.vue'
import Search from '../../components/Search.vue'
import SearchInput from '../../components/SearchInput.vue'
import expend from './components/expend.vue'
import activeExpend from './components/activeExpend.vue'

const { message } = inject('Feedback')
const store = useStore()
const hasEditPermission = computed(() => store.getters['user/isSalesSupport'])
const expandedRowKeys = ref([])
// 当前页码
const current = ref(1)
// 每页条数
const pageSize = ref(10)
// 筛选条件
const clientName = ref('')
const url = ref('')
const mailbox = ref('')
const status = ref('-1')
// 展开数据
const columnDataL = ref()
const columnDataP = ref()
const uploadInput = ref(null)
const loading = ref(false)
const columns = reactive(pageColumns.accountPool)
/**
 * 行展开、收起
 * @param expanded
 * @param record
 */
const handleRowExpand = async (expanded, record) => {
  if (expanded) {
    expandedRowKeys.value.splice(
      expandedRowKeys.value.findIndex(key => key === record.key),
      1
    )
  } else {
    store.commit('ADMIN_LAST_PROJECT_INFO', {})
    store.commit('ADMIN_CLIENT_PHASE_INFO', {})
    if (record.status === 11) {
      await store
        .dispatch('setAdminLastProjectInfo', {
          clientID: record.id
        })
        .then(() => {
          columnDataL.value = JSON.parse(JSON.stringify(data.value))
          if (
            (!lastProjectInfo.value.total || lastProjectInfo.value.total === 0) &&
            (!lastProjectInfo.value.list || lastProjectInfo.value.list.length === 0)
          ) {
            columnDataL.value[record.key].list = { total: '', list: [] }
          } else {
            columnDataL.value[record.key].list = lastProjectInfo.value
          }
          store.commit('ADMIN_POOL_TABLE', columnDataL.value)
        })
        .then(() => {
          expandedRowKeys.value.push(record.key)
        })
        .finally(() => {
          clearLoading()
        })
    } else {
      await store
        .dispatch('setAdminClientPhaseInfo', {
          clientID: record.id
        })
        .then(() => {
          columnDataP.value = JSON.parse(JSON.stringify(data.value))
          if (
            !clientPhaseInfo.value ||
            clientPhaseInfo.value.length === 0 ||
            JSON.stringify(clientPhaseInfo.value) === '{}'
          ) {
            columnDataP.value[record.key].clientPhaseInfo = {
              clientShareList: [],
              clientPhareList: [
                { entryDateAdd: '', displayName: '' },
                { entryDateAdd: '', displayName: '' },
                { entryDateAdd: '', displayName: '' },
                { entryDateAdd: '', displayName: '' }
              ]
            }
          } else {
            columnDataP.value[record.key].clientPhaseInfo = clientPhaseInfo.value
          }
          store.commit('ADMIN_POOL_TABLE', columnDataP.value)
        })
        .then(() => {
          expandedRowKeys.value.push(record.key)
        })
        .finally(() => {
          clearLoading()
        })
    }
  }
}
/**
 * 搜索
 */
const handleSearch = () => {
  if (clientName.value === '' && url.value === '' && mailbox.value === '' && status.value === '-1') {
    message.error('Please specify at least one search filter')
    store.commit('ADMIN_POOL_TABLE', [])
    store.commit('ADMIN_TOTAL', 0)
    return
  }
  expandedRowKeys.value = []
  current.value = 1
  getList()
}
/**
 * 重置
 */
const handleReset = () => {
  clientName.value = ''
  url.value = ''
  mailbox.value = ''
  status.value = '-1'
  clearData()
}
/**
 * 获取列表数据
 * @returns {Promise<void>}
 */
const getList = async () => {
  loading.value = true
  await store
    .dispatch('setAdminPoolTable', {
      clientName: clientName.value.trim(),
      url: url.value.trim(),
      mailbox: mailbox.value.trim(),
      status: Number(status.value),
      page: {
        pageRows: pageSize.value,
        pageIndex: current.value,
        total: 0
      }
    })
    .finally(() => {
      clearLoading()
    })
}
/**
 * 切换页码
 * @param cur
 */
const changeSize = cur => {
  current.value = cur
  expandedRowKeys.value = []
  getList()
}
/**
 * 表格数据
 * @type {ComputedRef<*>}
 */
const data = computed(() => store.state.pool.adminPoolTable)
/**
 * 总条数
 * @type {ComputedRef<*>}
 */
const total = computed(() => store.state.pool.adminTotal)
/**
 * status === 11时展开
 * @type {ComputedRef<{}|*>}
 */
const lastProjectInfo = computed(() => store.state.pool.adminLastProjectInfo)
/**
 * status !=== 11时展开
 * @type {ComputedRef<{}|*>}
 */
const clientPhaseInfo = computed(() => store.state.pool.adminClientPhaseInfo)
/**
 * 下载
 */
const handleDownload = () => {
  Pool.downloadTemplate().then(res => {
    Util.downloadBlob(res, 'Template.xlsx', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
  })
}
/**
 * 导入
 */
const handleImport = () => {
  uploadInput.value.click()
}
/**
 * 文件上传
 * @param event
 */
const uploadFileChange = event => {
  if (event.target.files[0].name.split('.').pop() !== 'xlsx') {
    message.error('Please upload Excel 2007 or higher version')
  } else {
    const name = event.target.files[0].name.split('.')[0]
    const fileForm = new FormData()
    fileForm.append('file', event.target.files[0])
    Pool.importClientPool(fileForm).then(res => {
      if (res.type === 'application/json') {
        const reader = new FileReader()
        reader.readAsText(res, 'utf-8')
        reader.onload = () => {
          if (JSON.parse(reader.result).code === 2000) {
            message.success(IMPORT_SUCCEEDED)
          } else {
            message.error('Excel Error!')
          }
        }
      } else {
        message.success("Download success, Please check your browser's download records")
        Util.downloadBlob(
          res,
          'result(' + name + ').xlsx',
          'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
        )
      }
      uploadInput.value.value = null
    })
  }
}
/**
 * 关闭loading
 */
const clearLoading = () => {
  setTimeout(() => {
    loading.value = false
  }, 30)
}
/**
 * 清空数据
 */
const clearData = () => {
  expandedRowKeys.value = []
  store.commit('ADMIN_POOL_TABLE', [])
  store.commit('ADMIN_LAST_PROJECT_INFO', {})
  store.commit('ADMIN_CLIENT_PHASE_INFO', {})
  store.commit('ADMIN_TOTAL', 0)
}
/**
 * 离开清空
 */
onBeforeUnmount(() => {
  clearData()
})
</script>
<style scoped lang="less">
@import '@/assets/style/reset_table';
@import '@/assets/style/reset_form';

.du-area {
  display: flex;
  justify-content: flex-end;
  margin-bottom: 10px;
  .button {
    display: flex;
    align-items: center;
  }
}
</style>
<route lang="yaml">
name: Account Pool Management
path: '/pool-m/client-pool'
meta:
  title: 'Client Pool'
  sort: 0
  roles: isPrimaryCSO, isBranchCSO, isBUM, isSalesSupport
</route>
